<template>
    <div class="container">
        <view class="content">
            <form>
                <!-- 表单内容 -->
                <view class="form-item">
                    <text class="label">收货人</text>
                    <input class="input" placeholder="请填写收货人姓名" v-model="form.contact" />
                </view>
                <view class="form-item">
                    <text class="label">手机号码</text>
                    <input class="input" placeholder="请填写收货人手机号码" v-model="form.mobile" @input="validateMobile"/>
                    <view v-if="mobileError && form.mobile" class="error-message">请输入正确的手机号</view>
                </view>
                <view class="form-item">
                    <text class="label">所在地区</text>
                    <view @click="openPicker" :class="{ 'has-location': form.fullLocation, 'placeholder': !form.fullLocation }">
                        {{ form.fullLocation || "请选择省/市/区(县)" }}
                    </view>
                </view>
                <view class="form-item">
                    <text class="label">详细地址</text>
                    <input class="input" placeholder="街道、楼牌号等信息" v-model="form.street" />
                </view>
                <view class="form-item">
                    <label class="label">设为默认地址</label>
                    <switch class="switch" color="#27ba9b" :checked="form.isDefault === 1" @change="onSwitchChange" />
                </view>
            </form>
        </view>
        <!-- 提交按钮 -->
        <button @click="onSubmit" class="button" :disabled="isSubmitDisabled">保存并使用</button>
        <lotusAddress v-on:choseVal="choseValue" :lotusAddressData="lotusAddressData"></lotusAddress>
    </div>
</template>

<script>
import lotusAddress from '../../components/Winglau14-lotusAddress/Winglau14-lotusAddress.vue';

export default {
    components: {
        lotusAddress
    },
    props: {
        id: {
            type: String,
            required: false
        }
    },
    computed: {
        title() {
            return this.id ? '修改地址' : '新建地址';
        },
        isSubmitDisabled() {
            return this.mobileError || !this.form.mobile || !this.form.contact || !this.form.street;
        }
    },
    watch: {
        id: {
            immediate: true,
            handler() {
                this.setNavigationBarTitle();
            }
        }
    },
    mounted() {
        this.setNavigationBarTitle();
        if (this.id) {
            this.getAddressDetails(this.id);  // 获取地址详情
        }
    },
    data() {
        return {
            form: {
                contact: '', // 收货人
                mobile: '', // 联系方式
                fullLocation: '',
                province: '', // 省
                city: '', // 市
                town: '', // 县
                street: '', // 详细地址
                isDefault: 0 // 默认地址，1为是，0为否
            },
            lotusAddressData: {
                visible: false,
                provinceName: '',
                cityName: '',
                townName: ''
            },
            mobileError: false // 手机号码错误标识
        }
    },
    methods: {
        setNavigationBarTitle() {
            const title = this.title;
            if (typeof uni !== 'undefined' && uni.setNavigationBarTitle) {
                uni.setNavigationBarTitle({
                    title
                });
            } else {
                document.title = title; // 适用于浏览器环境
            }
        },
        // 获取地址详情
        getAddressDetails(id) {
            // 请求地址详情
            this.$service({
                url: `/addresses/${id}`,
                method: 'GET'
            }).then(res => {
                if (res.code === 0) {
                    this.form = { ...res.data };

                    // 设置 fullLocation 和 lotusAddressData
                    this.form.fullLocation = `${res.data.province} ${res.data.city} ${res.data.town}`;
                    this.lotusAddressData = {
                        visible: false,
                        provinceName: res.data.province,
                        cityName: res.data.city,
                        townName: res.data.town
                    };
                } else {
                    uni.showToast({
                        title: '获取地址详情失败',
                        icon: 'none'
                    });
                }
            }).catch(error => {
                console.error('请求失败:', error);
                uni.showToast({
                    title: '网络错误',
                    icon: 'none'
                });
            });
        },
        // 打开地区选择器
        openPicker() {
            this.lotusAddressData.visible = true;
        },
        // 回传已选的省市区的值
        choseValue(res) {
            this.lotusAddressData.visible = res.visible; // 控制picker组件显示和隐藏
            if (res.isChose) {
                this.form.province = res.province; // 省
                this.form.city = res.city; // 市
                this.form.town = res.town; // 区
                this.form.fullLocation = `${res.province} ${res.city} ${res.town}`; // 更新 fullLocation
            }
        },
        // 验证手机号
        validateMobile() {
            const mobilePattern = /^[1-9]\d{10}$/;
            this.mobileError = this.form.mobile && !mobilePattern.test(this.form.mobile);
        },
        // 切换默认地址
        onSwitchChange(ev) {
            this.form.isDefault = ev.mp.detail.value ? 1 : 0;
        },
        // 表单提交
        async onSubmit() {
            if (this.mobileError) {
                uni.showToast({
                    icon: 'none',
                    title: '请输入正确的手机号'
                });
                return;
            }

            // 根据id判断是新增地址还是修改地址
            const url = '/addresses';
            const method = this.id ? 'PUT' : 'POST';

            // 提交表单
            this.$service({
                url,
                method,
                data: this.form
            }).then(res => {
                if (res.code === 0) {
                    uni.showToast({
                        icon: 'success',
                        title: this.id ? '修改成功' : '添加成功'
                    });
                    setTimeout(() => {
                        uni.navigateBack();
                    }, 400);
                } else {
                    uni.showToast({
                        icon: 'none',
                        title: '提交失败'
                    });
                }
            }).catch(error => {
                console.error('请求失败:', error);
                uni.showToast({
                    icon: 'none',
                    title: '网络错误'
                });
            });
        }
    }
}
</script>

<style lang="scss">
@import './addFormStyles.scss';

.error-message {
    color: red;
    font-size: 12px;
    margin-top: 5px;
}
</style>
